package com.seari.custody.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.seari.custody.bean.*;
import com.seari.custody.component.MinIoUtil;
import com.seari.custody.constant.BusinessConstant;
import com.seari.custody.constant.MessageConstant;
import com.seari.custody.pojo.MessageBean;
import com.seari.custody.service.ProjectManageService;
import com.seari.custody.service.TechnicalAdviceService;
import com.seari.custody.util.HandlerNullUtils;
import com.seari.custody.util.JwtTokenUtils;
import io.minio.ObjectStat;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@Slf4j
@RequestMapping("/projectManage")
public class ProjectManageController {

    @Autowired
    private ProjectManageService projectManageService;

    @Autowired
    private TechnicalAdviceService technicalAdviceService;

    @Value("${minio.word}")
    private String minioword;

    @Value("${minio.pdf}")
    private String miniopdf;

    @Value("${minio.otherfilebypromanage.bucket}")
    private String otherfilebypromanage;

    @Autowired
    private MinIoUtil minIoUtil;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 根据年月判断日期
     *
     * @param date
     * @return
     */
    private static int howManyDays(String date) {
        Calendar calendar = Calendar.getInstance();
        String[] dates = date.split("[^\\d]");
        int year = Integer.parseInt(dates[0]);
        int month = Integer.parseInt(dates[1]) - 1;
        calendar.set(year, month, 1);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    @RequestMapping("/queryProListByProperty")
    public MessageBean queryProListByProperty(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        MessageBean messageBean = new MessageBean();
        try {
//            String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
//            String userNumber = JwtTokenUtils.getUserNumber(tokenHeader.substring(JwtTokenUtils.TOKEN_PREFIX.length()));//用户账号
//            String userNumber="01010006421";
            Integer pageNum = (Integer) map.get("page");
            Integer pageSize = (Integer) map.get("limit");
            String selectType = (String) map.get("selectType");
            String startTime = "";
            String endTime = "";

            //开始时间
            if (!HandlerNullUtils.objectIsNull(map.get("startTime"))) {
                startTime = map.get("startTime") + "-01";
            }
            //结束时间
            if (!HandlerNullUtils.objectIsNull(map.get("endTime"))) {
                endTime = (String) map.get("endTime");
                endTime = endTime + "-" + howManyDays(endTime);
            }
            //排序
            String sort = "0";
            if (!HandlerNullUtils.objectIsNull(map.get("sort"))) {
                sort = (String) map.get("sort");
            }
            //项目名称
            String projectNameSelect = null;
            if (!HandlerNullUtils.objectIsNull(map.get("projectName"))) {
                projectNameSelect = (String) map.get("projectName");
            }
            pageNum = pageNum == null ? 1 : pageNum;
            pageSize = pageSize == null ? 10 : pageSize;
            int pageNumInt = pageNum;
            int pageSizeInt = pageSize;

            List<Map<String, String>> projectList = new ArrayList<Map<String, String>>();
            PageHelper.startPage(pageNumInt, pageSizeInt);
            //projectList = projectManageService.queryProListByProperty(BusinessConstant.VERSION_TYPE_NEW,selectType,userNumber,sort,projectNameSelect,startTime,endTime);
            projectList = projectManageService.queryProListByProperty(BusinessConstant.VERSION_TYPE_NEW, selectType, null, sort, projectNameSelect, startTime, endTime,null);
            PageInfo<Map<String, String>> page = new PageInfo<Map<String, String>>(projectList);

            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("projectList", page);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("列表查询项目信息成功 ");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("列表查询项目信息失败");
        }
        return messageBean;
    }

    /**
     * 二级
     *
     * @param map
     * @return
     */
    @RequestMapping("/queryProCateByProID")
    public MessageBean queryProCateByProID(@RequestBody Map<String, Object> map) {
        MessageBean messageBean = new MessageBean();
        try {
            String proID = (String) map.get("proID");
            String proType = (String) map.get("proType");
            Map<String, Object> dataMap = new HashMap<String, Object>();
            Map<String, String> folderMap = new LinkedHashMap<>();
            folderMap.put("-1", "其他");
            if ("project".equals(proType)) {
                Project project = projectManageService.queryProByProID(proID);
                switch (project.getType()) {
                    case "5":
                        folderMap.put(BusinessConstant.SELECR_TYPE_JHDG, "监护大纲");
                        folderMap.put(BusinessConstant.SELECR_TYPE_XK, "技术审查（许可）");
                        folderMap.put(BusinessConstant.SELECR_TYPE_ZXBHFA, "专项保护方案");
                        break;
                    case "6":
                        folderMap.put("5", "结合改造");
                        break;
                    default:
                        folderMap.put(BusinessConstant.SELECR_TYPE_ZX, "技术审查（征询）");
                        break;
                }
                dataMap.put("project", project);
            } else if ("newfolder".equals(proType)) {
                CreateFolder createFolder = projectManageService.queryFolderByID(proID);
                dataMap.put("project", createFolder);
            }
            dataMap.put("folder", folderMap);
            dataMap.put("proType", proType);
            dataMap.put("proID", proID);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("列表查询项目信息成功 ");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("列表查询项目信息失败");
        }
        return messageBean;
    }

    /**
     * 三级
     *
     * @param map
     * @return
     */
    @RequestMapping("/queryProCate")
    public MessageBean queryProCate(@RequestBody Map<String, Object> map) {
        MessageBean messageBean = new MessageBean();
        try {
            String proID = (String) map.get("proID");
            String cate = (String) map.get("cate");
            String proType = (String) map.get("proType");

            Map<String, Object> dataMap = new HashMap<String, Object>();
            Map<String, Object> folderMap = new LinkedHashMap<>();
            String reviewStatus = null;

            switch (cate) {
                case "-1"://其他
                    List<String> idList = new ArrayList<>();
                    List<CreateFolder> folderList = projectManageService.queryFolderByProID(proID);
                    idList.add(proID);
                    for (CreateFolder c : folderList) {
                        idList.add(c.getId().toString());
                    }
                    if ("newfolder".equals(proType)) {
                        idList.add(proID);
                    }
                    List<OtherFile> list = projectManageService.queryOtherFileByFolderID(idList,null);
                    dataMap.put("otherFile", list);
                    break;
                case BusinessConstant.SELECR_TYPE_JHDG://监护大纲
                    List<String> projectList = projectManageService.queryOutlineNumber(proID);
                    for (String num : projectList) {
                        folderMap.put("监护大纲第" + num + "次", num);
                    }
                    folderMap.put("报价单","-1");
                    dataMap.put("folder", folderMap);
                    break;
                case BusinessConstant.SELECR_TYPE_ZX://征询
                    List<String> projectListZX = projectManageService.queryFlowNumber(proID);
                    for (String num : projectListZX) {
                        folderMap.put("征询第" + num + "次", num);
                    }
                    dataMap.put("folder", folderMap);
                    break;
                case BusinessConstant.SELECR_TYPE_XK://许可
                    List<String> projectListXK = projectManageService.queryFlowNumber(proID);
                    for (String num : projectListXK) {
                        folderMap.put("许可第" + num + "次", num);
                    }
                    dataMap.put("folder", folderMap);
                    break;
                case BusinessConstant.SELECR_TYPE_ZXBHFA://专项保护方案
                    List<String> projectListZXBH = projectManageService.queryFlowNumber(proID);
                    for (String num : projectListZXBH) {
                        folderMap.put("专项保护方案第" + num + "次", num);
                    }
                    dataMap.put("folder", folderMap);
                    break;
                default://结合改造

                    break;
            }
            dataMap.put("cate", cate);
            dataMap.put("proType", proType);
            dataMap.put("proID", proID);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("列表查询项目信息成功 ");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("列表查询项目信息失败");
        }
        return messageBean;
    }

    /**
     * 四级
     *
     * @param map
     * @return
     */
    @RequestMapping("/queryProDetailsByProID")
    public MessageBean queryProDetailsByProID(@RequestBody Map<String, Object> map) {
        MessageBean messageBean = new MessageBean();
        try {
            String proID = (String) map.get("proID");
            String cate = (String) map.get("cate");
            String num = (String) map.get("num");//次数
            List<String> numList=new ArrayList<>();
            for(int i=Integer.parseInt(num);i>=1;i--){
                numList.add(i+"");
            }
            Map<String, Object> dataMap = new HashMap<String, Object>();
            Project project = projectManageService.queryProDetailsByProID(proID);
            //全部的文件  保含工程信息概况
            List<File> fileLists = new ArrayList<>();

            //获取项目附件上传接口
            List<TechnicalAccessory> technicalAccessoryList = technicalAdviceService.getTechnicalAccessoryListByProjectUuid(proID);

            String reviewStatus = null;
            switch (cate) {
                case BusinessConstant.SELECR_TYPE_JHDG://监护大纲
                    /**--------------------监护大纲流程状态-------------------*/
                    List<String> listJH = new ArrayList<>();
                    listJH.add("待处理");
                    listJH.add("资料校对a");
                    listJH.add("处理中");
                    listJH.add("已发送");
                    listJH.add("技术要求表被退回待处理a");
                    listJH.add("技术要求表被修改待确认a");
                    listJH.add("已完结");
                    Map<String, String> jhMap = new LinkedHashMap<>();
                    jhMap.putAll(BusinessConstant.outlineStatus);//复制原监护大纲流程
                    dataMap.put("flowList", flowList(jhMap, listJH, num, proID, "2", 1));

                    /**--------------------监护大纲项目文档-------------------*/
                    fileLists = projectManageService.getProFileByProID(proID, null, numList);
                    project.setFiles(fileLists);
                    break;

                case BusinessConstant.SELECR_TYPE_ZX://征询
                    /**--------------------征询流程状态-------------------*/
                    List<String> listZX = new ArrayList<>();
                    listZX.add("待处理");
                    listZX.add("资料校对a");
                    listZX.add("处理中");
                    listZX.add("专项草稿审核");
                    listZX.add("技审草稿被退回待处理a");
                    listZX.add("已完结");
                    Map<String, String> zxMap = new LinkedHashMap<>();
                    zxMap.putAll(BusinessConstant.projectManagementMap);//复制原流程

                    zxMap.remove("7");
                    zxMap.remove("8");
                    zxMap.remove("9");
                    dataMap.put("flowList", flowList(zxMap, listZX, num, proID, "1", 1));

                    /**--------------------征询项目文档-------------------*/
                    reviewStatus = "2";
                    List<Map<String, String>> technicalAdvicesZX = projectManageService.queryTechnicalAdviceFileByForProManage(proID, reviewStatus);

                    if(technicalAdvicesZX.size()>0) {
                        Map<String, String> fristZXTechnicalAdvice = technicalAdvicesZX.get(0);
                        fristZXTechnicalAdvice.put("flag", "终稿");
                        addUrl(fristZXTechnicalAdvice);
                        for (int i = 1; i < technicalAdvicesZX.size(); i++) {
                            Map<String, String> technicalAdvice = technicalAdvicesZX.get(i);
                            technicalAdvice.put("flag", "过程稿");
                            addUrl(technicalAdvice);
                        }
                    }

                    fileLists = projectManageService.getProFileByProID(proID, numList, null);
                    project.setFiles(fileLists);
                    dataMap.put("technicalAdviceListZX", technicalAdvicesZX);
                    break;
                case BusinessConstant.SELECR_TYPE_XK://许可
                    /**--------------------许可流程状态-------------------*/
                    List<String> listXK = new ArrayList<>();
                    listXK.add("待处理");
                    listXK.add("资料校对a");
                    listXK.add("处理中");
                    listXK.add("专项草稿审核");
                    listXK.add("技审草稿被退回待处理a");
                    listXK.add("已完结");
                    Map<String, String> xkMap = new LinkedHashMap<>();
                    xkMap.putAll(BusinessConstant.projectManagementMap);//复制原流程

                    xkMap.remove("7");
                    xkMap.remove("8");
                    xkMap.remove("9");
                    dataMap.put("flowList", flowList(xkMap, listXK, num, proID, "1", 1));

                    /**--------许可项目文档-----------*/
                    reviewStatus = "1";
                    //技审意见
                    // Map<String,Object> fileMap=new HashMap<>();
                    List<Map<String, String>> technicalAdvicesXK = projectManageService.queryTechnicalAdviceFileByForProManage(proID, reviewStatus);
                    List<Map<String, String>> technicalAdviceList = new ArrayList<>();
                    Map<String, String> finalVersion = new HashMap<>();
//                    if(specialProtections.size()>0){
//                        specialProtection=specialProtections.get(0);
//                        for(Map<String,String> technicalAdvice:technicalAdvicesXK){
//                            addUrl(technicalAdvice);
//                            if(technicalAdvice.get("fileID").equals(specialProtection.get("no"))){//技审意见终稿
//                                technicalAdvice.put("flag","终稿");
//                                finalVersion=technicalAdvice;
//                            }else{
//                                technicalAdvice.put("flag","过程稿");
//                                technicalAdviceList.add(technicalAdvice);
//                            }
//                        }
//                        technicalAdviceList.add(finalVersion);
//                    }else{
//                        for(Map<String,String> technicalAdvice:technicalAdvicesXK){
//                            technicalAdvice.put("flag","过程稿");
//                            addUrl(technicalAdvice);
//                            technicalAdviceList.add(technicalAdvice);
//                        }
//                    }
                    if(technicalAdvicesXK.size()>0) {
                        Map<String, String> fristTechnicalAdvice = technicalAdvicesXK.get(0);
                        fristTechnicalAdvice.put("flag", "终稿");
                        addUrl(fristTechnicalAdvice);
                        technicalAdviceList.add(fristTechnicalAdvice);
                        for (int i = 1; i < technicalAdvicesXK.size(); i++) {
                            Map<String, String> technicalAdvice = technicalAdvicesXK.get(i);
                            technicalAdvice.put("flag", "过程稿");
                            addUrl(technicalAdvice);
                            technicalAdviceList.add(technicalAdvice);
                        }
                    }

                    fileLists = projectManageService.getProFileByProID(proID, numList, null);
                    project.setFiles(fileLists);
                    dataMap.put("technicalAdviceListXK", technicalAdviceList);

                    break;
                case BusinessConstant.SELECR_TYPE_ZXBHFA://专项保护方案
                    /**--------------------专项保护流程状态-------------------*/
                    List<String> listZXBH = new ArrayList<>();
                    listZXBH.add("待处理");
                    listZXBH.add("资料校对a");
                    listZXBH.add("处理中");
                    listZXBH.add("专项草稿审核");
                    listZXBH.add("技审草稿被退回待处理a");
                    listZXBH.add("已完结");
                    listZXBH.add("处理中");
                    listZXBH.add("已退回a");
                    listZXBH.add("已完结");
                    Map<String, String> zxbhMap = new LinkedHashMap<>();
                    zxbhMap.putAll(BusinessConstant.projectManagementMap);//复制原流程
                    zxbhMap.remove("1");
                    zxbhMap.remove("2");
                    zxbhMap.remove("3");
                    zxbhMap.remove("4");
                    zxbhMap.remove("5");
                    zxbhMap.remove("6");
                    dataMap.put("flowList", flowList(zxbhMap, listZXBH, num, proID, "1", 7));

                    /**--------专项保护项目文档-----------*/
                    List<Map<String, String>> specialProtections = projectManageService.querySpecialProtectionFileByForProManage(proID);

                    for (Map<String, String> specialProtection:specialProtections){
                        specialProtection.put("flag", "过程稿");
                        addUrl(specialProtection);
                    }
                    for (Map<String, String> specialProtection:specialProtections){
                        if("报审系统".equals(specialProtection.get("source"))){
                            specialProtection.put("flag", "终稿");
                            break;
                        }
                    }
                    dataMap.put("specialProtection", specialProtections);
                    fileLists = projectManageService.getProFileByProID(proID, numList, null);
                    project.setFiles(fileLists);
                    break;
                default://结合改造

                    break;
            }

            dataMap.put("project", project);
            dataMap.put("technicalAccessoryList", technicalAccessoryList);
            dataMap.put("cate", cate);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("获取项目的详情信息成功 ");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("获取项目的详情信息失败");
        }
        return messageBean;
    }

    /**
     * 新建
     *
     * @param map
     * @return
     */
    @RequestMapping("/createFolder")
    public MessageBean createFolder(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        MessageBean messageBean = new MessageBean();
        try {
            String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
            String userNumber = JwtTokenUtils.getUserNumber(tokenHeader.substring(JwtTokenUtils.TOKEN_PREFIX.length()));
//            String userNumber = "01010006406";
            String folderName = (String) map.get("folderName");
            CreateFolder createFolder = projectManageService.insertCreateFolder(folderName,userNumber);
            if(createFolder.getId()==-1){
                messageBean.setData(createFolder.getId());
                messageBean.setType(MessageConstant.FAIL_TYPE);
                messageBean.setCode(MessageConstant.FAIL);
                messageBean.setMessage("文件夹重名，新建失败！");
            }else {
                messageBean.setData(createFolder.getId());
                messageBean.setType(MessageConstant.SUCCESS_TYPE);
                messageBean.setCode(MessageConstant.SUCCESS);
                messageBean.setMessage("文件夹新建成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("文件夹新建失败");
        }
        return messageBean;
    }

    /**
     * 其他文件上传
     *
     * @return
     */
    @RequestMapping("/uploadFile")
    public MessageBean uploadFile(String folderID, HttpServletRequest request) {
        MessageBean messageBean = new MessageBean();
        try {
            String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
            String userNumber = JwtTokenUtils.getUserNumber(tokenHeader.substring(JwtTokenUtils.TOKEN_PREFIX.length()));
//            String userNumber="01010006406";
            List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");

            List<String> list = new ArrayList<>();
            for (int i = 0; i < files.size(); i++) {
                MultipartFile file = files.get(i);
                InputStream is = file.getInputStream(); //得到文件流
                String fileName = file.getOriginalFilename(); //文件名
                list.add(fileName);
                String contentType = file.getContentType();  //类型
                if (!file.isEmpty()) {
                    //把文件放置Minio桶(文件夹)
                    OtherFile otherFile = new OtherFile();
                    otherFile.setFolderID(folderID);
                    otherFile.setFileName(fileName);
                    otherFile.setStatus("1");
                    otherFile.setCreateUser(userNumber);
                    otherFile.setCreateTime(sdf.format(new Date()));
                    otherFile.setUpdateUser(userNumber);
                    otherFile.setUpdateTime(sdf.format(new Date()));
                    projectManageService.insertOtherFile(otherFile);

                    //MinIoUtil.getInstance().putObject(otherfilebypromanage, fileName, is, contentType);
                    minIoUtil.putObject(otherfilebypromanage, fileName, is, contentType);
                }
            }
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("文件上传成功 ");
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("文件上传失败");
        }
        return messageBean;
    }

    /**
     * 其他文件下载
     *
     * @return
     */
    @RequestMapping("/downloadFile")
    public void downloadFile(HttpServletResponse response, @RequestParam Map<String, Object> map) {
        try {
            //附件ID
            String fileID = (String) map.get("fileID");
            OtherFile otherFile = projectManageService.queryFileByID(fileID);
            ObjectStat objectStat = minIoUtil.getObjectStat(otherfilebypromanage, otherFile.getFileName());
            response.setContentType(objectStat.contentType());
            response.setCharacterEncoding("UTF-8");
            //设置响应头
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(otherFile.getFileName(), "UTF-8"));
            //文件流
            InputStream object = minIoUtil.getObject(otherfilebypromanage, otherFile.getFileName());
            IOUtils.copy(object, response.getOutputStream());
            object.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 移动
     *
     * @param map
     * @return
     */
    @RequestMapping("/moveFolder")
    public MessageBean moveFolder(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        MessageBean messageBean = new MessageBean();
        try {
            String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
            String userNumber = JwtTokenUtils.getUserNumber(tokenHeader.substring(JwtTokenUtils.TOKEN_PREFIX.length()));
//            String userNumber="01010006406";
            List<String> moveFileID = (List<String>) map.get("moveFileID");//被移动文件夹的id
            String proID = (String) map.get("proID");//目的地文件夹id

            String oldFileID = "";
            for (String id : moveFileID) {
                OtherFile otherFile = projectManageService.queryFileByID(id);
                oldFileID = otherFile.getFolderID();
                otherFile.setFolderID(proID);
                otherFile.setUpdateUser(userNumber);
                otherFile.setUpdateTime(sdf.format(new Date()));
                projectManageService.updateOtherFile(otherFile);
            }
            CreateFolder oldFolder = projectManageService.queryFolderByID(oldFileID);
            if (oldFolder != null) {
                List<String> idList = new ArrayList<>();
                idList.add(oldFileID);
                List<OtherFile> list = projectManageService.queryOtherFileByFolderID(idList,null);
                if (list.size() == 0) {//判断原文件夹中内容是否被全部移除
                    oldFolder.setStatus("0");
                }
                oldFolder.setUpdateTime(sdf.format(new Date()));
                oldFolder.setUpdateUser(userNumber);
                oldFolder.setStatus("0");
                projectManageService.updateCreateFolder(oldFolder);
            }
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("文件夹移动成功 ");
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("文件夹移动失败");
        }
        return messageBean;
    }

    /**
     * 移动（1）显示可移动文件
     *
     * @param map
     * @return
     */
    @RequestMapping("/selMoveFile")
    public MessageBean selMoveFile(@RequestBody Map<String, Object> map) {
        MessageBean messageBean = new MessageBean();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            String proID = (String) map.get("proID");//项目ID
            String fileName=(String) map.get("fileName");
            List<String> idList = new ArrayList<>();
            List<CreateFolder> folderList = projectManageService.queryFolderByProID(proID);
            idList.add(proID);
            for (CreateFolder c : folderList) {
                idList.add(c.getId().toString());
            }
            idList.add(proID);
            List<OtherFile> list = projectManageService.queryOtherFileByFolderID(idList,fileName);
            List<Map<String, Object>> result=new ArrayList<>();
            List<Map<String, String>> p = projectManageService.queryProListByProperty(BusinessConstant.VERSION_TYPE_NEW,
                    null,null,null,null,null,null,proID);
            if(p.size()>0) {
                Map<String, Object> pro = new HashMap<>();
                pro.put("id", proID);
                pro.put("pId", "-1");
                pro.put("name", p.get(0).get("proNmae"));
                pro.put("open:", true);
                pro.put("drag", false);
                result.add(pro);
            }
            Map<String, Object> other=new HashMap<>();
            other.put("id","1");
            other.put("pId",proID);
            other.put("name","其他");
            other.put("open:",true);
            other.put("drag",false);
            result.add(other);
            for(OtherFile o:list){
                Map<String, Object> file=new HashMap<>();
                file.put("id",o.getId().toString());
                file.put("pId","1");
                file.put("name",o.getFileName());
                result.add(file);
            }
            dataMap.put("zNodes", result);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("列表查询成功 ");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("列表查询失败");
        }
        return messageBean;
    }

    /**
     * 移动（2）显示可移动至的项目
     *
     * @param map
     * @return
     */
    @RequestMapping("/selMovePro")
    public MessageBean selMovePro(@RequestBody Map<String, Object> map) {
        MessageBean messageBean = new MessageBean();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            String proID = (String) map.get("proID");//项目ID
            String proName= (String) map.get("proName");
            List<Map<String, String>> list = projectManageService.queryProListByProperty(BusinessConstant.VERSION_TYPE_NEW, null, null, null, proName, null, null,null);
            List<Map<String, Object>> result = new ArrayList<>();
            for (int i=0;i<list.size();i++) {
                Map<String, String> m=list.get(i);
                if (!m.get("proID").equals(proID)) {
                    result.addAll(addFiles(m,i+""));
                }
            }
            dataMap.put("zNodes", result);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("列表查询成功 ");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("列表查询失败");
        }
        return messageBean;
    }

    /**
     * 拼接url
     *
     * @param map
     */
    public void addUrl(Map<String, String> map) {
        //Word文件名
        String wordName = map.get("wordName");
        String wordU = minioword + wordName;
        map.put("wordUrl", wordU);
        ;
        //pdf文件名
        String pdfName = map.get("pdfName");
        String pdfU = miniopdf + pdfName;
        map.put("pdfUrl", pdfU);
    }

    /**
     * 流程状态
     *
     * @param flowMap
     * @param list
     * @param num
     * @param proID
     * @param type
     * @return
     */
    public List<Map<String, String>> flowList(Map<String, String> flowMap, List<String> list, String num, String proID, String type, int f) {
        List<Map<String, String>> resultJH = new ArrayList<>();
        for (String flowJH : flowMap.keySet()) {
            if ("1".equals(flowJH)) {//待处理状态
                Map<String, String> fristFlowJH = new HashMap<>();
                if ("1".equals(type)) {
                    fristFlowJH = projectManageService.queryFristFlow(num, proID, null);
                } else {
                    fristFlowJH = projectManageService.queryFristFlow(null, proID, num);
                }
                if (fristFlowJH.get("create_time") != null && fristFlowJH.get("create_time").trim() != null) {
                    fristFlowJH.put("flag", "1");
                    resultJH.add(fristFlowJH);
                } else {
                    fristFlowJH.put("flag", "0");
                    resultJH.add(fristFlowJH);
                }
            } else {
                List<Map<String, String>> flowStatusListJH = projectManageService.queryFlowStatus(type, proID, flowJH, num);
                if (flowStatusListJH.size() > 0) {//历史表中有当前状态的记录
                    Map<String, String> flow = flowStatusListJH.get(0);
                    f = Integer.parseInt(flow.get("flow"));
                    flow.put("flow", flowMap.get(flowJH));
                    flow.put("flag", "1");
                    resultJH.add(flow);
                    if (f == 2) {
                        break;
                    }
                }
            }
        }
        //补齐常规状态
        List<String> listJH2 = new ArrayList<>();
        if (f != 2) {
            for (int i = f; i < list.size(); i++) {
                listJH2.add(list.get(i));
            }
            if ("1".equals(type) && f == 7 && resultJH.size() == 0) {//专项保护方案的处理中
                Map<String, String> m = new HashMap<>();
                m.put("flag", "0");
                m.put("flow", "处理中");
                resultJH.add(m);
            }
            for (String str : listJH2) {
                if (!str.contains("a")) {
                    Map<String, String> m = new HashMap<>();
                    m.put("flag", "0");
                    m.put("flow", str);
                    resultJH.add(m);
                }
            }
        }
        return resultJH;
    }


    /**
     * 移动框列表展示 项目添加文件
     * @param proMap
     * @param otherId
     * @return
     */
    public List<Map<String, Object>> addFiles(Map<String, String> proMap,String otherId){
        String proID=proMap.get("proID");
        //取出项目其他文件
        List<String> idList = new ArrayList<>();
        List<CreateFolder> folderList = projectManageService.queryFolderByProID(proID);
        idList.add(proID);
        for (CreateFolder c : folderList) {
            idList.add(c.getId().toString());
        }
        idList.add(proID);
        List<OtherFile> fileList = projectManageService.queryOtherFileByFolderID(idList,null);

        List<Map<String, Object>> result=new ArrayList<>();
        Map<String, Object> pro=new HashMap<>();
        pro.put("id",proID);
        pro.put("pId","-1");
        pro.put("name",proMap.get("proNmae"));
        pro.put("open:",true);
        pro.put("drag",false);
        result.add(pro);
        Map<String, Object> other=new HashMap<>();
        other.put("id",otherId);
        other.put("pId",proID);
        other.put("name","其他");
        other.put("open:",true);
        other.put("drag",false);
        result.add(other);
        for(OtherFile o:fileList){
            Map<String, Object> file=new HashMap<>();
            file.put("id",o.getId().toString());
            file.put("pId",otherId);
            file.put("name",o.getFileName());
            result.add(file);
        }
        return result;
    }


}
